#!/usr/bin/python
# -*- coding: utf-8 -*-

import urllib, cookielib, urllib2
import sys, logging, os
from sgmllib import SGMLParser

loginURL = "https://uis1.fudan.edu.cn/amserver/UI/Login?goto=http://www.urp.fudan.edu.cn/index.portal"
scoreURL = "http://www.urp.fudan.edu.cn:84/epstar/app/fudan/ScoreManger/ScoreViewer/Student/Course.jsp"
logoutURL = "http://www.urp.fudan.edu.cn/logout.jsp"

def getHTML(user, passwd, captcha = None):
    sys.stdout.flush()
    cookie = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
    urllib2.install_opener(opener)
    str = urllib.urlencode({'IDToken1': user, 'IDToken2': passwd})
    sock1 = urllib2.urlopen(loginURL, str)
    loginHTML = sock1.read()
    logging.debug(loginHTML)
    sock1.close()

    sock2 = urllib2.urlopen(scoreURL)
    scoreHTML = sock2.read()
    logging.debug(scoreHTML)
    sock2.close()

    sock3 = urllib2.urlopen(logoutURL)
    sock3.close()

    return scoreHTML

class URPParser(SGMLParser):
    def reset(self):
        self.tdOpen = False
        self.strongOpen = False
        self.list = []
        self.started = True
        SGMLParser.reset(self)

    def start_strong(self, attrs):
        self.strongOpen = True

    def end_strong(self):
        self.strongOpen = False

    def start_tr(self, attrs):
        self.row = []

    def end_tr(self):
        if self.started and self.row != []:
            self.list.append(self.row)
            self.row = []

    def start_td(self, attrs):
        for (k, v) in attrs:
            if (k == "align"):
                self.tdOpen = True
                break

    def end_td(self):
        self.tdOpen = False

    def handle_data(self, text):
        if (self.tdOpen):
            if (len(text.strip()) > 0):
                self.row.append(text.strip())

    def result(self):
        return self.list

if __name__ == '__main__':
    if os.path.exists('gpa.html'):
        f = open('gpa.html', 'r')
        html = f.read()
        f.close()
    else:
        user = raw_input('username: ')
        pword = raw_input('password: ')
        html = getHTML(user, pword)
        open('gpa.html', 'w').write(html)
    parser = URPParser()
    parser.feed(html)
    result = parser.result()
    for line in result:
        print ", ".join(str.decode('utf-8').encode('gbk') for str in line)